package cn.edu.xjtu.carlWay.tree.pathSumII;

import cn.edu.xjtu.Util.TreeNode.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 113. 路径总和 II
 * 给你二叉树的根节点 root 和一个整数目标和 targetSum ，找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
 * <p>
 * 叶子节点 是指没有子节点的节点。
 * <p>
 * https://leetcode-cn.com/problems/path-sum-ii/
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> pathList = new ArrayList<>();
        pathHelp(root, targetSum, new ArrayList<Integer>(), pathList);
        return pathList;
    }

    private void pathHelp(TreeNode root, int targetSum, ArrayList<Integer> path, List<List<Integer>> pathList) {
        if (root == null) {
            return;
        }
        int leftVal = targetSum - root.val;
        path.add(root.val);
        if (leftVal == 0 && root.left == null && root.right == null) {
            pathList.add((List<Integer>) path.clone());
        } else {
            pathHelp(root.left, leftVal, path, pathList);
            pathHelp(root.right, leftVal, path, pathList);
        }
        path.remove(path.size() - 1);
    }
}
